package sunmi.payment.L3;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;

import mi.payment.MyApplication;
import mi.payment.constants.Params;
import mi.payment.controller.ParamsInitCtrl;
import mi.payment.db.UserInfoModel;
import mi.payment.interfaces.ITaskListener.DefaultTaskListener;
import mi.payment.ui.base.ParentActivity;
import mi.payment.utils.UIUtils;
import sunmi.sunmiui.utils.LogUtil;

/**
 * L3 界面路由器
 *
 * @author Lee64 on 2017/4/26.
 */

public class L3Route extends ParentActivity {

    private static final String TAG = "L3Route";

    private int connectCount; // 初始化连接支付服务次数

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        // 屏幕独占
        UIUtils.screenMonopoly(1);

        // 初始化默认用户
        mUserInfoModel.initTable();

        // 默认01进入
        Params.userInfo = UserInfoModel.getInstance().queryUserInfoById("01");

        // 获取Intent数据
        getIntentData();

        startTransaction();
    }

    public void handleTransaction() {
        L3Handler handler = new L3Handler(this);
        final int transType = Params.sL3Params.transType;
        boolean finish = true;
        // 判断交易笔数上限
        boolean over = L3TransactionUtil.isTransactionNumberOver();
        LogUtil.d(TAG, "判断交易笔数上限:" + over);
        switch (transType) {
            case 0:
            case 21:
                // 消费、订单支付接口(通联支持)
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    handler.handleConsume();
                }
                break;
            case 1:
                // 消费撤销
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    finish = false;
                    handler.handleConsumeRevocation();
                }
                break;
            case 2:
                // 退货
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    handler.handleReturnGoods();
                }
                break;
            case 3:
                // 预授权
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    handler.handlePreAuthorizeConsume();
                }
                break;
            case 4:
                // 预授权撤销
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    handler.handlePreAuthorizeRevoke();
                }
                break;
            case 5:
                // 预授权完成
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    handler.handlePreAuthorizeComplete();
                }
                break;
            case 6:
                // 预授权完成撤销
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    handler.handlePreAuthorizeCompleteRevoke();
                }
                break;
            case 7:
                // 结算
                finish = false;
                handler.handleSettlement();
                break;
            case 8:
                // 签到
                finish = false;
                handler.handleSignIn();
                break;
            case 9:
                // 余额查询
                handler.handleQueryBalance();
                break;
            case 10:
                // 系统管理
                handler.handleSystemManagement();
                break;
            case 11:
                // 打印
                handler.handlePrint();
                break;
            case 13:
                // 商户信息查询
                handler.handleQueryMerchantInfo();
                break;
            case 15:
                // 签退
                finish = false;
                handler.handleSignOut();
                break;
            case 12:
            case 16:
            case 17:
                // 联机交易记录查询
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    finish = false;
                    handler.handleQueryByOnline();
                }
                break;
            case 18:
                // 本地交易记录查询
                handler.handleQueryByLocal();
                break;
            case 20:
                // 设置签购单抬头
                handler.handleRiseString();
                break;
            case 22:
                // 订单支付结果查询(通联支持)
                if (over) {
                    finish = true;
                    L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_NUM_LIMIT);
                } else {
                    finish = false;
                    handler.handleOrderQuery();
                }
                break;
            default:
                L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_INVALID_TRADE_TYPE);
                break;
        }
        if (finish) {
            finish();
        }
    }


    private void startTransaction() {
        // 连接PayHardwareService成功？
        boolean isDisconnect = L3TransactionUtil.isDisconnectPayHardwareService();
        LogUtil.d(TAG, "isDisconnect:" + isDisconnect);
        if (isDisconnect) {
            mHandler.sendEmptyMessageDelayed(0, 500);
            return;
        }

        // 判断是否签到
        boolean isNotSign = L3TransactionUtil.isNotSign();
        LogUtil.d(TAG, "判断是否签到:" + isNotSign);
        if (isNotSign) {
            sign();
            return;
        }

        if (Params.sL3Params == null) {
            L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_FAILED);
            finish();
            return;
        }

        // 判断交易开关
        boolean isClose = L3TransactionUtil.isTransactionSwitchClose(Params.sL3Params.transType, Params.sL3Params.paymentType);
        LogUtil.d(TAG, "判断交易开关:" + isClose);
        if (isClose) {
            L3BroadcastHelper.sendFailedBroadcast(this, L3ErrorCode.ERROR_TRADE_CLOSE);
            finish();
            return;
        }

        handleTransaction();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // 连接PayHardwareService
            if (connectCount >= 5 && MyApplication.getInstance().pinPadOpt == null) {
                mHandler.removeCallbacksAndMessages(null);
                L3BroadcastHelper.sendFailedBroadcast(L3Route.this, L3ErrorCode.ERROR_INITIALIZED_FAIL);
                finish();
                return;
            }
            connectCount++;
            if (MyApplication.getInstance().pinPadOpt != null) {
                mHandler.removeCallbacksAndMessages(null);
                startTransaction();
            } else {
                mHandler.sendEmptyMessageDelayed(0, 500);
            }
        }

    };

    /**
     * 签到
     */
    private void sign() {
        ParamsInitCtrl ctrl = new ParamsInitCtrl(this);
        ctrl.paramsInit(new DefaultTaskListener<String>() {

            @Override
            public void onTaskSuccess(String ret) {
                startTransaction();
            }

            @Override
            public void onTaskFailed(String ret) {
                L3BroadcastHelper.sendFailedBroadcast(L3Route.this, L3ErrorCode.ERROR_TRADE_FAILED, ret);
                finish();
            }

        });
    }

    /**
     * 获取Intent数据
     */
    private void getIntentData() {
        final Intent intent = getIntent();
        Params.initL3Params();
        L3Params params = Params.sL3Params;
        params.transType = intent.getIntExtra(L3Constant.RequestParameterName.REQ_TRANS_TYPE, -99999);
        params.appId = intent.getStringExtra(L3Constant.RequestParameterName.REQ_APP_ID);
        params.transId = intent.getStringExtra(L3Constant.RequestParameterName.REQ_TRANS_ID);

        params.amount = intent.getLongExtra(L3Constant.RequestParameterName.REQ_AMOUNT, -99999L);
        params.paymentType = intent.getIntExtra(L3Constant.RequestParameterName.REQ_PAYMENT_TYPE, -99999);

        params.oriVoucherNo = intent.getStringExtra(L3Constant.RequestParameterName.REQ_ORI_VOUCHER_NO);
        params.oriReferenceNo = intent.getStringExtra(L3Constant.RequestParameterName.REQ_ORI_REFERENCE_NO);
        params.oriAuthNo = intent.getStringExtra(L3Constant.RequestParameterName.REQ_ORI_AUTH_NO);
        params.oriQROrderNo = intent.getStringExtra(L3Constant.RequestParameterName.REQ_ORI_QR_ORDER_NO);
        params.oriTransDate = intent.getStringExtra(L3Constant.RequestParameterName.REQ_ORI_TRANS_DATE);

        // 打印附加数据
        String printInfo = intent.getStringExtra(L3Constant.RequestParameterName.REQ_PRINT_INFO);
        String printInfo2 = intent.getStringExtra(L3Constant.RequestParameterName.REQ_PRINT_INFO2);
        String printMerchantInfo = intent.getStringExtra(L3Constant.RequestParameterName.REQ_PRINT_MERCHANT_INFO);
        String printMerchantInfo2 = intent.getStringExtra(L3Constant.RequestParameterName.REQ_PRINT_MERCHANT_INFO2);
        if (printInfo != null && printInfo.length() > 100) {
            printInfo = printInfo.substring(0, 100);
        }
        if (printMerchantInfo != null && printMerchantInfo.length() > 100) {
            printMerchantInfo = printMerchantInfo.substring(0, 100);
        }
        params.isPrintTicket = intent.getBooleanExtra(L3Constant.RequestParameterName.REQ_IS_PRINT_TICKET, true);
        params.printInfo = printInfo;
        params.printInfo2 = printInfo2;
        params.printMerchantInfo = printMerchantInfo;
        params.printMerchantInfo2 = printMerchantInfo2;

        // 打印
        params.isOnlyPrint = intent.getBooleanExtra(L3Constant.RequestParameterName.REQ_IS_ONLY_PRINT, false); // 是否直接打印
        params.isLastTrade = intent.getBooleanExtra(L3Constant.RequestParameterName.REQ_IS_LAST_TRADE, false);
        params.lastTradeType = intent.getIntExtra(L3Constant.RequestParameterName.REQ_LAST_TRADE_TYPE, 0); // 末笔类型

        // 结算
        params.isSettlementDetail = intent.getBooleanExtra(L3Constant.RequestParameterName.REQ_IS_SETTLEMENT_DETAIL, false);
        boolean isPrintSettleTicket = intent.getBooleanExtra(L3Constant.RequestParameterName.REQ_IS_PRINT_SETTLE_TICKET, true);
        if (isPrintSettleTicket) {
            // 仅对 transType=7 结算交易生效。非必填，默认值为 true。
            // 所以isPrintTicket可以不赋值
        } else {
            params.isPrintTicket = false;
        }
        params.riseString = intent.getStringExtra(L3Constant.RequestParameterName.REQ_RISE_STRING);
        params.isManagePwd = intent.getBooleanExtra(L3Constant.RequestParameterName.REQ_IS_MANAGE_PWD, false);
        params.reserve = intent.getStringExtra(L3Constant.RequestParameterName.REQ_RESERVE);
    }


}
